import React, { FC, useMemo, useState } from "react";

const UseMemoDemo: FC = () => {
  console.log("rerender");

  const [num1, setNum1] = useState(10);
  const [num2, setNum2] = useState(20);
  const [text, setText] = useState("hello"); // 更新就会导致组件rerender

  const sum = useMemo(() => {
    console.log("gen sum..."); // 缓存 rerender不会在执行

    return num1 + num2;
  }, [num1, num2]);

  return (
    <>
      <p>{sum}</p>
      <p>
        {num1} <button onClick={() => setNum1(num1 + 1)}>add num1</button>
      </p>
      <p>
        {num2} <button onClick={() => setNum2(num2 + 1)}>add num2</button>
      </p>
      <div>
        {/* form 组件,受控组件,类似Vue的双向绑定 */}
        <input
          type="text"
          onChange={(e) => setText(e.target.value)}
          value={text}
        />
      </div>
    </>
  );
};

export default UseMemoDemo;
